package xyz.tommy0607.calculator

import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import xyz.tommy0607.calculator.view.RoundButton
import kotlin.math.floor

class MainActivity : AppCompatActivity() {
    private var preNumber = 0.0
    private var preOperatorId = -1
    private var currOperatorId = -1
    private lateinit var numberInput: TextView
    private val operatorButtons = arrayOfNulls<RoundButton>(4)
    //数字区域是否留存着上次运算的结果
    private var inputHasPreNumber=false

    private val colorOperatorBg
        get() = ContextCompat.getColor(this, R.color.operatorButtonBg)
    private val colorOperatorText
        get() = ContextCompat.getColor(this, R.color.operatorButtonText)

    companion object {
        private const val OPERATOR_ADD = 0
        private const val OPERATOR_SUB = 1
        private const val OPERATOR_MUL = 2
        private const val OPERATOR_DIV = 3
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val rootView = findViewById<ViewGroup>(R.id.rootView)
        for (i in 1..5) {
            val rowView = rootView.getChildAt(i) as ViewGroup
            for (j in 0..3) {
                val button = rowView.getChildAt(j)
                val tag = button.tag as String
                button.tag = tag[1] - '0'
                when (tag[0]) {
                    'n' -> button.setOnClickListener(NumberClickListener())
                    'o' -> {
                        button.setOnClickListener(OperatorClickListener())
                        operatorButtons[tag[1] - '0'] = button as RoundButton
                    }
                    't' -> button.setOnClickListener(OtherClickListener())
                }
            }
        }
        numberInput = findViewById(R.id.numberInput)

    }



    private fun chooseOperator(operatorId: Int) {
        operatorButtons[operatorId]!!.setCircleColorWithAnimation(colorOperatorText)
        operatorButtons[operatorId]!!.setTextColorWithAnimation(colorOperatorBg)
    }

    private fun unchooseOperator(operatorId: Int) {
        operatorButtons[operatorId]!!.setCircleColorWithAnimation(colorOperatorBg)
        operatorButtons[operatorId]!!.setTextColorWithAnimation(colorOperatorText)
    }

    private fun parseNumberInput(): Double {
        return numberInput.text.toString().toDouble()
    }

    private fun updateNumberInput(number: Double) {
        if (number - floor(number) < 1e-4) {
            numberInput.text = number.toInt().toString()
        } else {
            var rawText = String.format("%f",number)
            if(rawText.contains('.')){
                while(rawText.endsWith('0')){
                    rawText=rawText.substring(0,rawText.length-1)
                }
            }
            numberInput.text=rawText
            inputHasPreNumber=true
        }
    }

    private inner class NumberClickListener : View.OnClickListener {
        override fun onClick(v: View?) {
            if (v == null) return
            val digit = v.tag as Int
            if (inputHasPreNumber) {
                preNumber = parseNumberInput()
                numberInput.text = ""
                if(currOperatorId!=-1) {
                    unchooseOperator(currOperatorId)
                    preOperatorId = currOperatorId
                    currOperatorId = -1
                }
                inputHasPreNumber=true
            }
            if (numberInput.text.toString() == "0") {
                numberInput.text = digit.toString()
            } else {
                numberInput.append(digit.toString())
            }
        }
    }

    private inner class OperatorClickListener : View.OnClickListener {
        override fun onClick(v: View?) {
            if (v == null) return
            if(preOperatorId!=-1){
                val currNumber = parseNumberInput()
                var answer = 0.0
                when (preOperatorId) {
                    OPERATOR_ADD -> answer = preNumber + currNumber
                    OPERATOR_SUB -> answer = preNumber - currNumber
                    OPERATOR_MUL -> answer = preNumber * currNumber
                    OPERATOR_DIV -> answer = preNumber / currNumber
                }
                updateNumberInput(answer)
            }
            val operatorId = v.tag as Int
            if (operatorId != currOperatorId) {
                chooseOperator(operatorId)
                if (currOperatorId > -1) {
                    unchooseOperator(currOperatorId)
                }
                currOperatorId = operatorId
            }
        }
    }

    private inner class OtherClickListener : View.OnClickListener {
        override fun onClick(v: View?) {
            if (v == null) return
            val id = v.tag as Int
            when (id) {
                0 -> {
                    numberInput.text = "0"
                }
                1 -> {
                    if (numberInput.text[0] == '-') {
                        numberInput.text = numberInput.text.substring(1)
                    } else {
                        numberInput.text = "-" + numberInput.text
                    }
                }
                3->{
                    if(!numberInput.text.contains('.')){
                        numberInput.append(".")
                    }
                }
                2 -> {
                    val number = parseNumberInput()
                    updateNumberInput(number * 0.01)
                }
                4 -> {
                    if(preOperatorId==-1)return
                    val currNumber = parseNumberInput()
                    var answer = 0.0
                    when (preOperatorId) {
                        OPERATOR_ADD-> answer = preNumber + currNumber
                        OPERATOR_SUB -> answer = preNumber - currNumber
                        OPERATOR_MUL -> answer = preNumber * currNumber
                        OPERATOR_DIV -> answer = preNumber / currNumber
                    }
                    updateNumberInput(answer)
                    preOperatorId=-1
                    preNumber=0.0
                }
            }
        }
    }
}